package cn.yuhh.api.helper;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 短信发送帮助类
 */
public class AliSMSHelper implements ISMSHelper {

    enum SmsType{
        VERIFY_CODE("广元消防", "SMS_167531710", new String[]{"code"}),

        RESTAURANT_NOTIFYING("广元消防", "SMS_173348222", new String[]{"name", "time", "merchant", "type"});

        private String signName;
        private String templateCode;
        private String[] params;

        SmsType(String signName, String templateCode, String[] params) {
            this.signName = signName;
            this.templateCode = templateCode;
            this.params = params;
        }

        public String getSignName() {
            return signName;
        }

        public String getTemplateCode() {
            return templateCode;
        }

        public String[] getParams() {
            return params;
        }
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private IAcsClient client;

    public AliSMSHelper(IAcsClient client) {
        this.client = client;
    }

    /**
     * 发送短信
     *
     * @param phoneNum 手机号
     * @param params   参数
     */
    public void send(String phoneNum, SmsType smsType, String... params) {
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("TemplateCode",smsType.getTemplateCode());
        request.putQueryParameter("SignName", smsType.getSignName());
        String[] paramsKey = smsType.getParams();
        if (paramsKey.length != params.length) {
            throw new IllegalStateException("参数异常");
        }
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < paramsKey.length; i++) {
            jsonObject.put(paramsKey[i], params[i]);
        }
        request.putQueryParameter("TemplateParam", jsonObject.toString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info("短信发送结果发送,phone:[{}],smsType:[{}], params:[{}], response:[{}]", phoneNum, params, response.getData());
        } catch (ClientException e) {
            logger.error("短信发送失败", e);
        }
    }


}
